package jp.co.iris_ltd.irisphotoeditor;

import java.util.HashMap;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.TypedArray;
import android.database.Cursor;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;

public class FilePickerActivity extends Activity {
    private class PhotoUriMapLoaderTaskHelper extends AsyncTask<Void, Void, HashMap<Integer, String>> {


        public PhotoUriMapLoaderTaskHelper() {
        }

        @Override
        protected HashMap<Integer, String> doInBackground(Void... params) {
            mIsWorking = true;
            final HashMap<Integer, String> uriMap = new HashMap<Integer, String>();
            Cursor cursor = managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null, null, null, null);
            cursor.moveToFirst();

            int fieldIndex;
            Long id;
            int cnt = 0;

            do {
                fieldIndex = cursor.getColumnIndex(MediaStore.Images.Media._ID);
                id = cursor.getLong(fieldIndex);

                Uri bmpUri = ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id);
                bmpUri.getPath();
                uriMap.put(cnt, getPath(bmpUri));
                cnt++;
            } while (cursor.moveToNext());

            return uriMap;
        }

        @Override
        protected void onPostExecute(HashMap<Integer, String> result) {
            mIsWorking = false;
            if (result != null && result.size() > 0) {
                final ImageContentsListAdapter adapter = new ImageContentsListAdapter(FilePickerActivity.this, getContentResolver(), result, result.size());
                loadingComplete(adapter);

                mGridList.setOnItemClickListener(new OnItemClickListener() {

                    @Override
                    public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
                        Intent intent = new Intent();
                        intent.putExtra(ITEM_TYPE_KEY, ITEM_TYPE_PHOTO);
                        intent.putExtra(FILE_PATH_KEY, (String) adapter.getItem(position));
                        setResult(RESULT_OK, intent);
                        finish();
                    }
                });
            } else {
                loadingFailed();
            }
        }
    }

    private String mDir;
    public static final String ITEM_TYPE_KEY = "item_type";
    public static final String FILE_PATH_KEY = "file_path";
    public static final String RESOUSE_NUMBER_KEY = "resouse_number";
    public static final int ITEM_TYPE_PHOTO = 0;
    public static final int ITEM_TYPE_STAMP = ITEM_TYPE_PHOTO + 1;
    public static final int ITEM_TYPE_RECTANGLE_FRAME = ITEM_TYPE_STAMP + 1;
    public static final int ITEM_TYPE_CORNER_FRAME = ITEM_TYPE_RECTANGLE_FRAME + 1;
    private int mItemType;
    private TypedArray mItems;
    private boolean mIsWorking = false;
    private TextView mListMessage;
    private ProgressBar mProgress;
    private GridView mGridList;
    private MediaScannerConnection mMediaScannerConnection;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.filelist);
        findViews();
        Intent intent = getIntent();
        mItemType = intent.getIntExtra(ITEM_TYPE_KEY, ITEM_TYPE_PHOTO);
        if (mItemType == ITEM_TYPE_PHOTO) {
            showPhotoList();
        } else {

            switch (mItemType) {
            case ITEM_TYPE_STAMP:
                mItems = getResources().obtainTypedArray(R.array.stamp_list);
                break;
            case ITEM_TYPE_RECTANGLE_FRAME:
                // TODO:
                break;
            case ITEM_TYPE_CORNER_FRAME:
                // TODO:
                break;
            default:
                break;
            }
            showResouseList(mItems);
        }
        ((Button) findViewById(R.id.btn_cancel)).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                finish();

            }
        });
    }

    private void showPhotoList() {
        PhotoUriMapLoaderTaskHelper loader = new PhotoUriMapLoaderTaskHelper();
        loader.execute();
    }

    private void showResouseList(final TypedArray items) {
        if (items != null) {
            if (items.length() != 0) {
                final ResouseListAdapter adapter = new ResouseListAdapter(this, R.layout.list_item_with_icon, items);

                loadingComplete(adapter);
                mGridList.setOnItemClickListener(new OnItemClickListener() {

                    @Override
                    public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
                        Intent intent = new Intent();
                        intent.putExtra(ITEM_TYPE_KEY, ITEM_TYPE_STAMP);
                        intent.putExtra(RESOUSE_NUMBER_KEY, position);
                        setResult(RESULT_OK, intent);
                        finish();
                    }
                });
            } else {
                loadingFailed();
            }

        }
    }

    private void findViews() {
        mListMessage = (TextView) findViewById(R.id.txt_list_message);
        mProgress = (ProgressBar) findViewById(R.id.progress);
        mGridList = (GridView) findViewById(R.id.grid_list);
    }

    @Override
    public void finish() {
        if (!mIsWorking) {
            super.finish();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mItemType == ITEM_TYPE_PHOTO) {
            SharedPreferences pref = this.getSharedPreferences("FIlePickerPrefs", MODE_PRIVATE);
            SharedPreferences.Editor editor = pref.edit();
            editor.putString("Folder", mDir);
            editor.commit();
        }
    }

    private void loadingFailed() {
        mListMessage.setVisibility(View.VISIBLE);
        mListMessage.setText(getResources().getString(R.string.filelist_empty));
        mProgress.setVisibility(View.GONE);
        mGridList.setVisibility(View.GONE);
    }

    private void loadingComplete(ListAdapter adapter) {
        mListMessage.setVisibility(View.GONE);
        mProgress.setVisibility(View.GONE);
        mGridList.setAdapter(adapter);
    }

    public String getPath(Uri uri) {
        ContentResolver contentResolver = getContentResolver();
        String[] columns = { MediaStore.Images.Media.DATA };
        Cursor cursor = contentResolver.query(uri, columns, null, null, null);
        cursor.moveToFirst();
        String path = cursor.getString(0);
        cursor.close();
        return path;
    }

    public void scanMedia(final String fp) {
        mMediaScannerConnection = new MediaScannerConnection(this, new MediaScannerConnection.MediaScannerConnectionClient() {
            @Override
            public void onScanCompleted(String path, Uri uri) {
                disconnect();
            }

            @Override
            public void onMediaScannerConnected() {
                scanFile(fp);

            }
        });
        mMediaScannerConnection.connect();
    }

    private void scanFile(String fp) {
        mMediaScannerConnection.scanFile(fp, "image/*");
    }

    private void disconnect() {
        mMediaScannerConnection.disconnect();
    }
}
